﻿using Day27Auth.Controllers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Day27Auth.Framework
{
    public class MVCActionTransform : IBundleTransform
    {
        public void Process(BundleContext context, BundleResponse response)
        {
            Bundle bundle = (context.BundleCollection
                .Where(b => b.Path == context.BundleVirtualPath)
                .FirstOrDefault());

            var writer1 = new StringWriter();
            AngularJSController c = new AngularJSController();
            //Create fake http context to render the view
            var fakeResponse = new HttpResponse(writer1);
            var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);


            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "AngularJS");
            routeData.Values.Add("action", "Routes");

            var fakeControllerContext = new ControllerContext(
                new HttpContextWrapper(fakeContext),
                routeData, c);


            var viewResult = ViewEngines.Engines.FindPartialView(fakeControllerContext, bundle.Path);
            var viewContext = new ViewContext(fakeControllerContext, viewResult.View, c.ViewData, c.TempData, writer1);
            viewResult.View.Render(viewContext, writer1);
            viewResult.ViewEngine.ReleaseView(fakeControllerContext, viewResult.View);
            //byte[] byteArray = Encoding.UTF8.GetBytes(writer1.ToString());
            //MemoryStream stream = new MemoryStream(byteArray);

            //return stream;
            
            response.Content = writer1.ToString();
            response.ContentType = "text/javascript";
        }
    }
}